package com.edu.whty.common.tools;

import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.cloud.Chapter;
import com.edu.whty.entity.usertextbook.TbUserTextbookCmsDir;
import com.edu.whty.entity.usertextbook.UserTextBook;
import com.edu.whty.service.UserTextBookService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CreateCmsFolderThread extends Thread {

    private static Logger logger = LoggerFactory.getLogger(CreateCmsFolderThread.class);

    @Autowired
	private static RedisUtil redisUtil;
    ;
    //过期时间
    static long expires = Constant.REDIS_DEFAULT_EXPIRES;
    @Autowired
    private static UserTextBookService userTextBookService = (UserTextBookService) SpringBeanFactory.getBean("userTextBookService");
    private Map<String, Object> paramMap;
    private UserTextBook book;
    private static String KEY_PREFIX = "resource";
    private static String SEPARATOR = "|";

    public CreateCmsFolderThread(Map<String, Object> paramMap, UserTextBook book) {
        this.paramMap = paramMap;
        this.book = book;
    }

    @Override
    public void run() {
        try {
            cmsCreateFolder(paramMap, book);
        } catch (Exception e) {
        }
    }

    /*
     * 缓存取数据
     */
    private static String getFromCache(String key, String url, String body) throws Exception {
        String val = (String) redisUtil.get(key);
        String resp = "";
        if (StringUtils.isEmpty(val) || StringUtils.isEmpty(key)) {
            long start = System.currentTimeMillis();

            //平台编码转换
            JSONObject reqJson = JSONObject.fromObject(body);
            if (reqJson.get("platformCode") != null) {
                reqJson.element("platformCode", "888888");
            }
            body = reqJson.toString();
            logger.info("url===" + url + "&param====" + body);


            resp = HttpClientUtil.post(url, body, null);
            long end = System.currentTimeMillis();
            if (end - start > Constant.TIME) {
                logger.error("cms long time  error: 接口请求url=" + url + "&param=" + body + "&time=" + (end - start));
            } else {
                logger.info("cms time : 接口请求url=" + url + "&param=" + body + "&time=" + (end - start));
            }
            redisUtil.set(key, resp, expires);
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("缓存获取 key：" + key + " value 值：" + resp);
            }
            resp = val;
        }
        return resp;
    }

    private static String getKeyQueryChapters(String body) {
        StringBuffer sb = new StringBuffer();
        if (body != null && !body.equals("")) {
            JSONObject reqJson = JSONObject.fromObject(body);
            sb.append(KEY_PREFIX).append(SEPARATOR).append("queryChapters").append(SEPARATOR).append(reqJson.getString("parentType"))
                    .append(SEPARATOR).append(reqJson.getString("parentId"))
                    .append(SEPARATOR).append(reqJson.getString("retType"));
        }
        return sb.toString();
    }

    @SuppressWarnings("rawtypes")
    private static String checkParam(String body) throws Exception {
        JSONObject reqJson = null;
        reqJson = JSONObject.fromObject((body == null || body.equals("")) ? "{}" : body);
        //参数检验
        if (!isNotNull(reqJson)) {
            throw new Exception("参数不存在");
        }
        return reqJson.toString();
    }

    /**
     * 判断对象是否为空
     *
     * @param o
     * @return
     */
    public static boolean isNotNull(Object o) {
        if (o == null) {
            return false;
        } else if (o instanceof String && "".equals(((String) o).trim())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 创建教材
     *
     * @param book
     * @return
     */
    public static String cmsCreateFolder(Map<String, Object> map) {
        String platformCode = SysConfig.getStrValue("platformCode");
        String dirId = "";
        JSONObject paramObject = new JSONObject();
        paramObject.put("dirName", "课程资源");
        paramObject.put("parentId", "0");
        paramObject.put("ownerType", "0");
        paramObject.put("userId", map.get("userId"));
        paramObject.put("canRemoved", "1");
        paramObject.put("resSource", "9");

        String url = String.valueOf(map.get("cms_createFolder"));
        logger.info("请求地址:" + url);
        logger.info("请求参数[platformCode=" + platformCode + "]：" + paramObject.toString());
        String result = null;

        try {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("platformCode", platformCode);
            result = HttpClientUtil.post(url, paramObject.toString(), headers, null);
            logger.info("返回信息:" + result);
            if (StringUtils.isNotEmpty(result)) {
                JSONObject resultJson = JSONObject.fromObject(result);
                if ("000000".equals(resultJson.optString("result"))) {
                    JSONObject data = resultJson.fromObject(resultJson.getJSONObject("data"));
                    dirId = data.optString("dirId");
                }
            }
        } catch (Exception e) {
            logger.error("文件夹失败[platformCode=" + platformCode + "]"
                    + "\n接口地址：" + url
                    + "\n接口参数：" + paramObject
                    + "\n接口返回：" + result, e);
            return null;
        }
        return dirId;
    }


    /**
     * 创建目录
     *
     * @param book
     * @return
     * @throws Exception
     */
    public static String cmsCreateFolder(Map<String, Object> map, UserTextBook book) throws Exception {

        JSONArray chapterListjson = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("parentId", map.get("textbookId"));
        param.put("parentType", "0");
        param.put("retType", "0");
        String body = param.toString();
        String jsonObj = getFromCache(getKeyQueryChapters(body)
                , String.valueOf(map.get("query_chapters")), checkParam(body));
        JSONObject resultObject = JSONObject.fromObject(jsonObj);
        String resultCode = resultObject.optString("result");
        JSONObject chapterJsonArr = null;
        if ("000000".equals(resultCode)) {
            chapterJsonArr = resultObject.optJSONObject("data");
            chapterListjson = chapterJsonArr.optJSONArray("list");
        }
        List<Chapter> querychapterList = (List<Chapter>) JSONArray.toCollection(chapterListjson, Chapter.class);

        //cms接口新建目录
        JSONObject paramObject = new JSONObject();
        String dirId = cmsCreateFolder(map);
        if (StringUtils.isEmpty(dirId)) {
            return null;
        }
        paramObject.put("ownerType", "0");
        paramObject.put("userId", map.get("userId"));
        paramObject.put("resSource", "9");

        JSONArray paramArray = new JSONArray();
        JSONObject paramObjectSub = null;
        paramObjectSub = new JSONObject();
        paramObjectSub.put("folderId", "0");
        paramObjectSub.put("diskParentId", dirId);
        paramObjectSub.put("folderName", book.getTextbookName());
        paramObjectSub.put("canRemoved", "1");
        paramArray.add(paramObjectSub);
        for (Chapter cha : querychapterList) {
            paramObjectSub = new JSONObject();
            paramObjectSub.put("folderId", cha.getChapterId());
            paramObjectSub.put("parentId", cha.getChapterPid());
            paramObjectSub.put("folderName", cha.getChapterTitle());
            paramObjectSub.put("canRemoved", "1");
            paramArray.add(paramObjectSub);
            List<Chapter> chas = cha.getChildChapterList();
            if (null != chas && chas.size() > 0) {
                for (Chapter ch : chas) {
                    paramObjectSub = new JSONObject();
                    paramObjectSub.put("folderId", ch.getChapterId());
                    paramObjectSub.put("parentId", ch.getChapterPid());
                    paramObjectSub.put("folderName", ch.getChapterTitle());
                    paramObjectSub.put("canRemoved", "1");
                    paramArray.add(paramObjectSub);
                }
            }


        }
        paramObject.put("folderList", paramArray);

        String url = String.valueOf(map.get("cms_batchCreateFolder"));
        logger.info("请求地址:" + url);
        logger.info("请求参数 ：" + paramObject.toString());
        String result = null;
        TbUserTextbookCmsDir cmsChapter = null;
        try {
            result = HttpClientUtil.post(url, paramObject.toString(), null);
            logger.info("返回信息:" + result);
            if (StringUtils.isNotEmpty(result)) {
                JSONObject resultJson = JSONObject.fromObject(result);
                if ("000000".equals(resultJson.optString("result"))) {
                    JSONObject object = resultJson.optJSONObject("data");
                    JSONArray data = object.optJSONArray("mapList");
                    if (data.size() > 0) {
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject o = JSONObject.fromObject(data.get(i));
                            cmsChapter = new TbUserTextbookCmsDir();

                            cmsChapter.setChapterId(o.optString("folderId"));
                            cmsChapter.setChapterName("");
                            cmsChapter.setTextbookId(book.getTextbookId());
                            cmsChapter.setTextbookName(book.getTextbookName());
                            cmsChapter.setUserId(String.valueOf(map.get("userId")));
                            cmsChapter.setUserName(book.getUserName());
                            cmsChapter.setDirId(o.optString("dirId"));

                            userTextBookService.addCmsChapter(cmsChapter);
                        }

                    }
                }
            }
        } catch (Exception e) {
            logger.error("添加文件目录失败[platformCode=]"
                    + "\n接口地址：" + url
                    + "\n接口参数：" + paramObject
                    + "\n接口返回：" + result, e);
            return null;
        }
        return null;
    }
}
